package app.r_teenus.backend.dao;

import java.util.List;

import javax.annotation.Resource;
import javax.xml.ws.WebServiceContext;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import app.r_teenus.backend.model.Device;
import app.r_teenus.backend.model.DeviceSearch;
import app.r_teenus.backend.model.DeviceType;
import app.r_teenus.backend.model.ServiceDevice;

@Repository("deviceDao")
@Transactional(readOnly = true)
public class DeviceDaoImpl extends DefaultDaoImpl implements DeviceDao {

	@Resource
	WebServiceContext wsContext;

	public Device findDeviceById(Integer id) {
		Device device = hibernateTemplate.get(Device.class, id);
		device.setDeviceTypeList(hibernateTemplate.loadAll(DeviceType.class));
		return device;
	}

	@Transactional(readOnly = false)
	public Device save(Device device) {
		hibernateTemplate.saveOrUpdate(device);
		return device;
	}

	public List<Device> findDevice() {
		return hibernateTemplate.loadAll(Device.class);
	}

	public Device createNewDevice() {
		Device device = new Device();
		device.setDeviceType(new DeviceType());
		device.setDeviceTypeList(hibernateTemplate.loadAll(DeviceType.class));
		return device;
	}

	public DeviceSearch createSearch() {
		DeviceSearch search = new DeviceSearch();
		search.setDevice(createNewDevice());
		return search;
	}

	public DeviceSearch search(DeviceSearch search) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Device.class);

		if (!search.getDevice().getName().isEmpty()) {
			criteria.add(Restrictions.eq("name", search.getDevice().getName()));
		}
		if (!search.getDevice().getModel().isEmpty()) {
			criteria.add(Restrictions.eq("model", search.getDevice().getModel()));
		}
		if (!search.getDevice().getRegNo().isEmpty()) {
			criteria.add(Restrictions.eq("regNo", search.getDevice().getRegNo()));
		}
		if (!search.getDevice().getRegNo().isEmpty()) {
			criteria.add(Restrictions.eq("regNo", search.getDevice().getRegNo()));
		}

		criteria.createAlias("deviceType", "deviceType");
		criteria.add(Restrictions.disjunction().add(Restrictions.eq("deviceType", search.getDevice().getDeviceType())));

		search.setDeviceList(hibernateTemplate.findByCriteria(criteria));
		
		for ( Device device : search.getDeviceList()){
			criteria = DetachedCriteria.forClass(ServiceDevice.class);
			criteria.createAlias("device", "device");
			criteria.add(Restrictions.disjunction().add(Restrictions.eq("device", device)));
			if(hibernateTemplate.findByCriteria(criteria).isEmpty()){
				device.setCanRemove(true);
			}
		}
		return search;
	}

	@Transactional(readOnly = false)
	public void delete(Device device) {
		device = (Device) hibernateTemplate.findByExample(device).get(0);
		hibernateTemplate.delete(device);
	}

}
